package socket.socket_1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

public class Server {
    private ServerSocket serverSocket;

    public Server() {
        System.out.println("正在启动服务端...");
        try {
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start() {

            while (true) {
                System.out.println("等待客户端连接....");
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("一个客户端连接了");
                HandlerClient hc = new HandlerClient(socket);
                Thread t = new Thread(hc);
                t.start();
            }
    }
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
    private class HandlerClient implements Runnable {
        private Socket socket;
        private String host;

        public  HandlerClient(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        @Override
        public void run() {
            try {
                /*
                通过Socket 获取输入流可以读取来自远端计算机发送过来的消息
                 */
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message = br.readLine()) != null) {
                    System.out.println(host + "说：" + message);
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

